import ApplyService from '../../services/apply'
import {
  noConsole,
} from '../../config';
import { getUpdatePage, getNonResultTips, getDataArrayByPage } from '../../utils/pagination'

const applyService = new ApplyService()
const noResultTips = '没有申请记录'
const noMoreResultTips = '没有更多申请记录'

export default {
  namespace: 'myApply',
  state: {
    applyList: [],  // 我的申请列表
    applyPage: 1,   // 当前申请列表页码
    applyNoneResultTips: '',   // 没有数据时的提示语
    applyNoneResult: false,    // 是否没有数据
    applyTotal: 0,   // 申请总数
    applyLastLoadTime: 0   // 最后加载时间
  },
  effects: {
    // 查询我的申请产品
    * getMyApply({ payload }, { call, put, select }) {
      
      // 清除没有数据的标志
      yield put({
        type: 'save', payload: {
          applyNoneResultTips: '',
          applyNoneResult: false,
          applyPage: payload.page,
        }
      });

      const { applyPage, applyList } = yield select(state => state.myApply)
      const { defaultPageSize } = yield select(state => state.common)

      const { data } = yield call(applyService.getMyOrder.bind(applyService), applyPage, defaultPageSize)
      const { current_page, last_page, total } = data

      if (Array.isArray(data.data)) {
        // 检查是否需要更新页数
        let updatePage = getUpdatePage(applyPage, current_page, last_page, data.data.length)
        
        const update: any = {
          applyList: getDataArrayByPage(current_page, last_page, defaultPageSize, total, applyList, data.data),
          applyPage: updatePage,
          applyTotal: total,
        }

        // 计算没有更多数据
        const noResult = getNonResultTips(current_page, data.data.length, defaultPageSize, noResultTips, noMoreResultTips)
        Object.assign(update, {
          applyNoneResult: noResult.noneResult,
          applyNoneResultTips: noResult.noneResultTips,
        })

        // 更新最后加载时间
        update.applyLastLoadTime = new Date().getTime()

        // 更新产品列表和页数
        yield put({ type: 'save', payload: update });
      }
    },
  },
  reducers: {
    // 更新state
    save(state, { payload }) {
      return { ...state, ...payload };
    },
  },
};
